#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
    void dfs(vector<int>& candidates, int target, vector<vector<int>> &answer, vector<int> &path, int sum, int start) {
        if (sum > target)  return;
        if (answer.size() >= 150) return;

        if (sum == target) {
            answer.push_back(path);
            return;
        }

        for (int i = start; i < candidates.size(); i++) {
            // 重复跳过
            if (i > start && candidates[i] ==  candidates[i-1]) continue;
    
            path.push_back(candidates[i]);
            dfs(candidates, target, answer, path, sum+candidates[i], i+1);
            path.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> answer;
        vector<int> path;
        std::sort(candidates.begin(), candidates.end());
        dfs(candidates, target, answer, path, 0, 0);
        return answer;
    }
};

int main(void)
{

    cout << "#40. 组合总和 II" << endl;
    cout << endl << "这个和 #39. 组合总和 II 基本一样，但是由于不能重复使用元素，增加了i+1,跳过当前元素; \n\
        又由于数组里有重复的数字，增加一个重复数组跳过" << endl;
    vector<int> candidates = {2,3,6,7};
    vector<vector<int>> ans = Solution().combinationSum2(candidates, 6);

    for (auto e: ans) {
        for (auto it: e)
            cout << it << ", ";
        cout << endl;
    }
    return 0;
}